﻿
using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Yuebon.WebApi.Common
{
    /// <summary>
    /// 对需要进行授权登录的接口生成对应的文档输入框，如Bearer Token
    /// </summary>
    public class HttpHeaderOperation: IOperationFilter
    {
        /// <summary>
        /// 实现Apply
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<IParameter>();
            }

            var actionAttrs = context.ApiDescription.ActionAttributes();
            var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
            // 查询是否过滤权限
            if (isAuthorized == false) //提供action都没有权限特性标记，检查控制器有没有
            {
                var controllerAttrs = context.ApiDescription.ControllerAttributes();
                isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
            }

            var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
            //operation.Parameters.Add(new NonBodyParameter()
            //{
            //    Name = "token",
            //    In = "header",
            //    Type = "string",
            //    Description = "token认证信息",
            //    Required = true
            //});
            if (isAuthorized && isAllowAnonymous == false)
            {
                
            }
        }
    }
}
